package com.lv.phuotbacnam.ui.fragment;

import java.io.ByteArrayOutputStream;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.android.gms.maps.model.LatLng;
import com.lv.phuotbacnam.R;
import com.lv.phuotbacnam.bl.callback.CallBackFromParse;
import com.lv.phuotbacnam.bl.callback.ThreadSafeResultCallback;
import com.lv.phuotbacnam.bl.data.BinhChonObject;
import com.lv.phuotbacnam.bl.data.DiaDiemObject;
import com.lv.phuotbacnam.bl.log.Logger;
import com.lv.phuotbacnam.bl.log.Toaster;
import com.lv.phuotbacnam.bl.network.error.ApplicationError;
import com.lv.phuotbacnam.bl.queries.BinhChonQueries;
import com.lv.phuotbacnam.bl.queries.DiaDiemQueries;
import com.lv.phuotbacnam.toolbox.ImageUtils;
import com.lv.phuotbacnam.ui.Section;
import com.lv.phuotbacnam.ui.activity.BackActivity;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.SaveCallback;

public class CreateNewDiaDiem extends BaseFragment {
	/* Load image activity result code */
	private final int RESULT_LOAD_IMAGE = 12323;

	/* Keys to define info of images */
	public static final String URL = "url";
//	public static final String NAME = "name";
//	public static final String TYPE = "__type";

	/* The info of all bitmaps that it was created from sdcard */
	JSONArray jsonArrayBitmap;

	/* The quantity of bitmaps that it was saved on Parse */
	int numberBitmapSaved = 0;

	public static LatLng vi_tri_da_chon;

	private ImageView currentExpectingImage;

	private Handler mHandler;

	/* The bitmaps that it was taken from sdcard */
	private Bitmap[] bitmaps;

	private int[] mListImageId = { R.id.cover_photo, R.id.add_image_one,
			R.id.add_image_two, R.id.add_image_three, R.id.add_image_four,
			R.id.add_image_five };

	private EditText ten_dia_diem;
	private EditText mo_ta;
	private TextView vi_tri;
	private TextView seekBarValue;
	private ImageView img_post;

	private ProgressBar pb_waiting;

	private int diem_binh_chon;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_create_new_dia_diem,
				container, false);

		initObject();
		setSeekBar(rootView);

		ten_dia_diem = (EditText) rootView.findViewById(R.id.ten_dia_diem);
		mo_ta = (EditText) rootView.findViewById(R.id.mo_ta);
		vi_tri = (TextView) rootView.findViewById(R.id.vi_tri);
		pb_waiting = (ProgressBar) rootView.findViewById(R.id.pb_waiting);
		img_post = (ImageView) rootView.findViewById(R.id.img_post);

		vi_tri.setOnClickListener(myOnClickListener);
		rootView.findViewById(R.id.img_post).setOnClickListener(
				myOnClickListener);

		rootView.findViewById(R.id.cover_photo).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_one).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_two).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_three).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_four).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_five).setOnClickListener(
				imageGetOnClickListener);

		return rootView;
	}

	/**
	 * To init object
	 */
	private void initObject() {
		bitmaps = new Bitmap[6];
		jsonArrayBitmap = new JSONArray();
		mHandler = new Handler();
	}

	/**
	 * To set seek bar binh chon diem
	 */
	private void setSeekBar(View rootView) {
		SeekBar seekBar = (SeekBar) rootView.findViewById(R.id.seekBarDistance);
		seekBar.setProgress(5);
		seekBar.incrementProgressBy(1);
		seekBar.setMax(10);
		seekBarValue = (TextView) rootView.findViewById(R.id.seekBarValue);
		// seekBarValue.setText(tvRadius.getText().toString().trim());

		seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				progress = progress / 1;
				progress = progress * 1;
				diem_binh_chon = progress;
				seekBarValue.setText(String.valueOf(progress));
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		vi_tri_da_chon = null;
	}

	@Override
	public void onStart() {
		super.onStart();
		if (vi_tri_da_chon != null)
			vi_tri.setText("( " + vi_tri_da_chon.latitude + ","
					+ vi_tri_da_chon.longitude + " )");
	}

	@Override
	public void applyStyles() {
		super.applyStyles();
		getNavigationController().getNavigationBar().setActionTitle("OK");

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// Get the selected image
		if (requestCode == RESULT_LOAD_IMAGE
				&& resultCode == Activity.RESULT_OK && null != data) {
			ImageUtils.decodeFromUri(
					getActivity(),
					data.getData(),
					new ThreadSafeResultCallback<Object, Bitmap>(Looper
							.getMainLooper()) {

						@Override
						public void doOnSuccess(Object request, Bitmap result) {
							/* show current expecting image to image view */
							currentExpectingImage.setImageBitmap(result);

							/* add bitmap to array list */
							for (int i = 0; i < mListImageId.length; i++)
								if (currentExpectingImage.getId() == mListImageId[i])
									bitmaps[i] = result;
						}

						@Override
						public void doOnError(ApplicationError error) {
						}
					});
		}
	}

	/**
	 * Handle onclick for image
	 */
	private View.OnClickListener imageGetOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			currentExpectingImage = (ImageView) v;
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, RESULT_LOAD_IMAGE);
		}
	};

	/**
	 * Handle onclick for others view
	 */
	private View.OnClickListener myOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.vi_tri:
				getNavigationController().navigateTo(BackActivity.class, false,
						Section.GOOGLE_MAP_CHON_VI_TRI, null);
				break;

			case R.id.img_post:
				getValue();
				break;

			default:
				break;
			}
		}

		/**
		 * To get data from ui
		 */
		private void getValue() {
			String ten_dia_diem_value = ten_dia_diem.getText().toString()
					.trim();
			String mo_ta_value = mo_ta.getText().toString();
			String vi_tri_value = vi_tri.getText().toString().trim();
			String seekBarValue_value = seekBarValue.getText().toString()
					.trim();
			//
			// Logger.logMessage("getValue");
			// Logger.logMessage("ten dia diem : " + ten_dia_diem_value);
			// Logger.logMessage("ten_bai_dang_value : " + ten_bai_dang_value);
			// Logger.logMessage("cam_nhan_value : " + cam_nhan_value);
			// Logger.logMessage("loi_khuyen_value : " + loi_khuyen_value);
			// Logger.logMessage("vi_tri_value : " + vi_tri_value);
			// Logger.logMessage("seekBarValue_value : " + seekBarValue_value);

			if (ten_dia_diem_value.equals("")) {
				ten_dia_diem.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.ten_dia_diem));
			} else if (vi_tri_value.equals("")) {
				vi_tri.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.vi_tri));
			} else if (mo_ta_value.equals("")) {
				mo_ta.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.mo_ta));
			} else if (seekBarValue_value.equals("")) {
				seekBarValue.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_binh_chon));
			} else if (jsonArrayBitmap == null)
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_chon_photo));
			else {
				ParseGeoPoint vi_tri_geoXY = new ParseGeoPoint(
						vi_tri_da_chon.latitude, vi_tri_da_chon.longitude);

				DiaDiemObject diaDiemObject = new DiaDiemObject(
						ten_dia_diem_value, vi_tri_geoXY, mo_ta_value,
						jsonArrayBitmap, 1, 1, 1, diem_binh_chon);
				saveData(diaDiemObject);
			}
		}
	};

	/**
	 * To save an image to Parse sever and get the info
	 */
	public void createImageParseFile(Bitmap bm) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
		final ParseFile pFile = new ParseFile("file", stream.toByteArray());
		pFile.saveInBackground(new SaveCallback() {
			@Override
			public void done(ParseException arg0) {
				try {
					JSONObject anImageObjec = new JSONObject();
					anImageObjec.put(URL, pFile.getUrl());
//					anImageObjec.put(NAME, pFile.getName());
//					anImageObjec.put(TYPE, "File");
					jsonArrayBitmap.put(anImageObjec);
					
				} catch (Exception e2) {
					Logger.logMessage("createImageParseFile Error");
				}
				numberBitmapSaved += 1;
			}
		});
	}

	/**
	 * To save KOEvent to Parse
	 */
	public void saveData(final DiaDiemObject diaDiemObject) {
		img_post.setVisibility(View.GONE);
		pb_waiting.setVisibility(View.VISIBLE);

		/* Save each bitmap to Parse server */
		for (int i = 0; i < bitmaps.length; i++)
			if (bitmaps[i] != null)
				createImageParseFile(bitmaps[i]);
			else
				numberBitmapSaved += 1;

		/* Check the number of bitmap that it was saved on Parse */
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (numberBitmapSaved >= bitmaps.length) {
					img_post.setVisibility(View.VISIBLE);
					pb_waiting.setVisibility(View.GONE);
					Toaster.showToast(getActivity(),
							getString(R.string.tao_dia_diem_moi));
					DiaDiemQueries.createNewDiaDiem(diaDiemObject,
							new CallBackFromParse<Object, ParseObject>() {
								@Override
								public void done(Object request,
										ParseObject diadiem) {
									BinhChonQueries.createNewBinhChon(
											new BinhChonObject(diem_binh_chon,
													""), diadiem);
								}
							});
					mHandler.removeCallbacks(this);
				} else
					mHandler.postDelayed(this, 500);
			}
		});
	}

}
